<script lang="ts">
// 普通的 script 块，用于定义静态选项
export default {
  name: 'ProjectDetail' // 基础组件名
}
</script>

<script setup lang="ts">
import { ref, computed, markRaw, onActivated, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { Message } from '@arco-design/web-vue'
import ProjectOverview from '@/views/missions/projects/detail/ProjectOverview.vue'
import TaskManage from '@/views/missions/projects/detail/TaskManage.vue'
import BugManage from '@/views/missions/projects/detail/BugManage.vue'
import {
  getProjectUsingGet,
  listProjectUsingGet,
  isProjectMemberUsingGet
} from '@/api/projectController'
import { useTeamStore, useUserStore } from '@/store'

const route = useRoute()
const router = useRouter()
const teamStore = useTeamStore()
const userStore = useUserStore()
// 项目列表
const projectList = ref<API.ProjectVo[]>([])

// 获取项目列表
const getProjectList = async () => {
  try {
    const res: any = await listProjectUsingGet({ teamId: teamStore.selectedTeam.id })
    if (res.code === 0) {
      projectList.value = res.data
    } else {
      Message.error(res.msg || '获取项目列表失败')
    }
  } catch (error) {
    console.error('获取项目列表失败:', error)
    Message.error('获取项目列表失败')
  }
}

// 当前项目信息
const currentProject = ref<API.ProjectVo>()

// 获取当前项目信息
const loading = ref(true)
// 获取当前项目
const getCurrentProject = async () => {
  loading.value = true
  try {
    const res: any = await getProjectUsingGet({
      id: Number(route.params.id)
    })
    if (res.code === 0) {
      currentProject.value = res.data
    } else {
      Message.error(res.msg || '获取项目信息失败')
    }
  } catch (error) {
    console.error('获取项目信息失败:', error)
    Message.error('获取项目信息失败')
  } finally {
    loading.value = false
  }
}

// 在组件激活时刷新数据
onActivated(async () => {
  await getCurrentProject()
  await getProjectList()
})

// 初始化数据
onMounted(async () => {
  //1. 判断我是否是项目成员或团队管理员 否拒绝访问
  const res: any = await isProjectMemberUsingGet({ proId: Number(route.params.id) })
  if (!res.data && !teamStore.isTeamAdmin) {
    Message.error('您不是项目成员或管理员，无法访问')
    //跳转到403
    router.push('/403')
    return
  }
  //当前页面是否已选择，选择后刷新页面应该保持选择,若不存在则默认选择概览
  const selected = localStorage.getItem('selectedTab')
  if (selected) {
    currentTab.value = JSON.parse(selected)
  } else {
    currentTab.value = 'overview'
  }
})

// 控制 popover 显示状态
const popoverVisible = ref(false)

// 处理 popover 显示状态变化
const handlePopoverVisibleChange = (visible: boolean) => {
  popoverVisible.value = visible
}

// 切换项目
const handleProjectChange = async (project: API.ProjectVo) => {
  router.push(`/missions/projects/${project.id}`)
  popoverVisible.value = false
}

// 标签页相关
const currentTab = ref()
const componentMap = {
  overview: markRaw(ProjectOverview),
  task: markRaw(TaskManage),
  bug: markRaw(BugManage)
}

const currentComponent = computed(() => {
  return componentMap[currentTab.value as keyof typeof componentMap]
})

const handleTabChange = (key: string) => {
  currentTab.value = key
  localStorage.setItem('selectedTab', JSON.stringify(key))
}

// 返回项目列表
const handleBackToList = () => {
  router.push('/missions/projects')
}
</script>

<template>
  <div class="project-detail">
    <div class="detail-header">
      <div class="header-content">
        <!-- 返回首页图标 -->
        <div class="home-link" @click="handleBackToList">
          <icon-home :style="{ fontSize: '20px' }" />
        </div>

        <!-- 项目名称下拉菜单 -->
        <a-popover
          trigger="click"
          position="bottom"
          :popup-visible="popoverVisible"
          @popup-visible-change="handlePopoverVisibleChange"
        >
          <div class="project-name-trigger">
            <h3 class="project-title">{{ currentProject?.title }}</h3>
            <icon-down class="trigger-icon" />
          </div>
          <template #content>
            <div class="project-list">
              <a-list :data="projectList" :bordered="false">
                <template #item="{ item }">
                  <a-list-item
                    class="project-item"
                    :class="{ active: item.id === currentProject?.id }"
                    @click="handleProjectChange(item)"
                  >
                    <span class="project-item-title">{{ item.title }}</span>
                  </a-list-item>
                </template>
              </a-list>
            </div>
          </template>
        </a-popover>

        <!-- 分隔符 -->
        <div class="divider"></div>

        <!-- 导航菜单 -->
        <a-menu mode="horizontal" :selected-keys="[currentTab]" @menu-item-click="handleTabChange">
          <a-menu-item key="overview">项目概览</a-menu-item>
          <a-menu-item key="task">任务管理</a-menu-item>
          <a-menu-item key="bug">DEBUG</a-menu-item>
        </a-menu>
      </div>
    </div>
    <div class="detail-content">
      <component :is="currentComponent" :proId="Number(route.params.id)" />
    </div>
  </div>
</template>

<style scoped>
.project-detail {
  display: flex;
  flex-direction: column;
  height: calc(100vh - 92px);
  background-color: var(--color-fill-2);
  border-radius: 4px;
}

.detail-header {
  padding: 16px 24px;
  border-bottom: 1px solid var(--color-border);
  flex-shrink: 0;
  background: #fff;
}

.header-content {
  display: flex;
  align-items: center;
}

.home-link {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 32px; /* 与项目名称高度一致 */
  cursor: pointer;
  color: var(--color-text-2);
  transition: all 0.2s;
  padding: 0 8px;
}

.home-link:hover {
  color: rgb(var(--primary-6));
}

.project-name-trigger {
  display: flex;
  align-items: center;
  height: 32px;
  gap: 8px;
  cursor: pointer;
  padding: 0 8px;
  transition: all 0.2s;
}

.divider {
  width: 1px;
  height: 20px;
  background-color: var(--color-border);
  margin: 0 16px;
}

.project-title {
  margin: 0;
  color: var(--color-text-1);
  font-size: 14px;
  font-weight: 500;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  line-height: 32px;
  transition: color 0.2s;
}

.trigger-icon {
  transition: color 0.2s;
}

/* 悬停效果 */
.project-name-trigger:hover {
  .project-title,
  .trigger-icon {
    color: rgb(var(--primary-6));
  }
}

.project-list {
  width: 200px;
  max-height: 400px;
  overflow: auto;
}

.project-item {
  cursor: pointer;
  padding: 8px 12px;
  transition: all 0.2s;
  border-radius: 4px;
  margin: 2px 0;
}

.project-item:hover {
  background-color: var(--color-fill-2);
}

.project-item.active {
  background-color: rgb(var(--primary-6));
  color: #fff;
}

.project-item-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 14px;
}

/* 修改 popover 相关样式 */
:deep(.arco-popover-content) {
  padding: 0;
}

:deep(.arco-popover) {
  background-color: var(--color-bg-2);
  box-shadow: 0 4px 10px rgba(var(--primary-6), 0.1);
  border: 1px solid rgba(var(--primary-6), 0.1);
}

:deep(.arco-menu-horizontal) {
  border-bottom: none;
}

:deep(.arco-menu-item) {
  padding: 0 16px;
}

.detail-content {
  flex: 1;
  min-height: 0;
  overflow: auto;
}
</style>
